#include <iostream>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
// 文件类
#include <fstream>
#include <cstdlib>
#include <cstring>

using namespace std;

// 得到 CPU利用率 和 内存空闲率
int main()
{
    // system("cat /proc/meminfo | grep MemTotal");
    ifstream ifs;

    // 打开文件
    ifs.open("/proc/meminfo");
    if (!ifs.is_open())
    {
        // 打开文件失败
        exit(-1);
    }

    // 临时存储一行内容的字符串
    char buffer[256] = {0};
    long memTotal = 0, memAvailable = 0;

    while (!ifs.eof())
    {
        // 读取一行
        ifs.getline(buffer, sizeof(buffer));
        if ((strstr(buffer, "MemTotal") != NULL))
        {
            string lineData(buffer);

            int startPos = 0;
            while (!isdigit(lineData[startPos]))
            {
                startPos++;
            }
            int endLen = 0;
            while (isdigit(lineData[startPos + endLen]))
            {
                endLen++;
            }
            memTotal = atoi(lineData.substr(startPos, endLen).c_str());
        }

        if ((strstr(buffer, "MemAvailable") != NULL))
        {
            string lineData(buffer);

            int startPos = 0;
            while (!isdigit(lineData[startPos]))
            {
                startPos++;
            }
            int endLen = 0;
            while (isdigit(lineData[startPos + endLen]))
            {
                endLen++;
            }
            memAvailable = atoi(lineData.substr(startPos, endLen).c_str());
        }
    }

    // 打印提取到的数值
    cout << "MemTotal: " << memTotal << " kB" << endl;
    cout << "MemAvailable: " << memAvailable << " kB" << endl;

    float usage = (float)(memAvailable * 100.0 / memTotal);
    cout << "usage:" << usage << endl;

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 绑定IP和端口
    struct sockaddr_in remoteAddress;
    memset(&remoteAddress, 0, sizeof(remoteAddress));
    remoteAddress.sin_family = AF_INET;
    remoteAddress.sin_port = htons(8080); // 转为大端
    const char *privateIp = "124.221.135.34";
    inet_pton(AF_INET, privateIp, (void *)&remoteAddress.sin_addr.s_addr);
    connect(sockfd, (struct sockaddr *)&remoteAddress, sizeof(remoteAddress));

    // 数据上报
    char data[64] = { 0 };
    while (1)
    {
        // 格式化字符串
        snprintf(data, sizeof(data), "memUsage:%.2f%%", usage);
        write(sockfd, &data, sizeof(data));
        sleep(3);
        memset(data, 0, sizeof(data));
    }

    return 0;
}